package com.ayu.a.practice01;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 徐林玉
 * @Description TwoSumPrac
 * @Date 2022/11/9 11:27
 * @Version 1.0
 */
public class TwoSumPrac {

    public static void main(String[] args) {

        int[] nums = new int[]{2,7,11,15};
        int target = 9;

        int[] arr = twoSum2(nums, target);

        for (int i = 0; i <arr.length ; i++) {

            System.out.print(arr[i]+"  ");
        }

    }


    public static int[] twoSum(int[] nums,int target){


        int[] arr = new int[2];
        for (int i = 0; i < nums.length ; i++) {



            for (int j = 0; j < nums.length; j++) {

                if(i!=j && (nums[i] + nums[j] == target)){


                    arr[0] = i;
                    arr[1] = j;
                    return arr;
                }
            }



        }

        return arr;

    }


    //使用map解决
    public static int[] twoSum2(int[] nums,int target){

        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {

            if(map.get(target-nums[i])!=null){

                return new int[]{map.get(target-nums[i]),i};

            }

            map.put(nums[i],i);

        }

        return new int[2];
    }

}
